"use strict";
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const dayjs = require("dayjs");

// app/controller/users.js
const Controller = require("egg").Controller;

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class FundController extends Controller {
  async getFundDetails() {
    const ctx = this.ctx;
    const fund_id = ctx.params.id;
    axios({
      method: "get",
      url: `http://fund.eastmoney.com/pingzhongdata/${fund_id}.js?v=${dayjs().format(
        "YYYYMMDDHHmmss"
      )}`,
      responseType: "stream",
    }).then(function (response) {
      mkdirsSync("static/fund/"); // 第一版，默认存到基金文件夹下
      response.data.pipe(fs.createWriteStream(`static/fund/${fund_id}.js`));
    });
  }
}

/**
 * @arg 创建指定路径
 * @使用示例  mkdirsSync('hello/a/b/c')
 * @说明      判断指定路径是否存在，若不存在，自动生成文件路径
 **/
function mkdirsSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

module.exports = FundController;
